package com.sxf.auth.captcha.controller;

import com.sxf.auth.captcha.service.ImageVerifyCodeService;
import com.sxf.auth.captcha.vo.CaptchaReq;
import com.sxf.auth.captcha.vo.CaptchaVO;
import com.sxf.auth.captcha.vo.VerifyImageVO;
import com.sxf.cache.CacheUtil;
import com.sxf.cache.EhcacheElementType;
import com.sxf.common.exceptions.BusinessException;
import com.sxf.common.param.ResultInfo;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


/**
 * @author Author
 * @description
 * @date 2020/4/15 8:58
 */
@Api(tags = "验证码服务")
@RestController
@RequestMapping("/captcha")
public class ImageVerifyCodeController {

    private static final Logger logger = LoggerFactory.getLogger(ImageVerifyCodeController.class);

    @Autowired
    private ImageVerifyCodeService imageVerifyCodeService;
    @Autowired
    CacheUtil cacheUtil;


    /**
     * @return BaseRestResult 返回类型
     * @description 生成滑块拼图验证码
     */
    @PostMapping(value = "/getImageVerifyCode")
    @ApiOperation(value = "获取图形验证码", produces = "application/json", httpMethod = "POST",hidden = true)
    public ResultInfo<VerifyImageVO> getImageVerifyCode() {
       return ResultInfo.success(imageVerifyCodeService.getImageVerifyCode());
    }

    /**
     * @return BaseRestResult 返回类型
     * @description 图形验证码
     */
    @PostMapping("/getCaptcha")
    @ApiOperation(value = "获取图形验证码", produces = "application/json", httpMethod = "POST")
    public ResultInfo<CaptchaVO> captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        logger.info("图形验证码值--{}",verCode);
        String key = UUID.randomUUID().toString();
        // 存入缓存并设置过期时间为5分钟
        cacheUtil.set(EhcacheElementType.CAPTCHA,key,verCode);
        // 将key和base64返回给前端
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setKey(key);
        captchaVO.setImage(specCaptcha.toBase64());
        return ResultInfo.success(captchaVO);
    }

    @PostMapping("/verifyCode")
    @ApiOperation(value = "图形验证码校验", produces = "application/json", httpMethod = "POST")
    public ResultInfo<Boolean> login(HttpServletRequest request, @RequestBody CaptchaReq req){
        // 获取redis中的验证码
        try{
            String redisCode = (String) cacheUtil.get(EhcacheElementType.CAPTCHA,req.getKey());
            if(redisCode == null){
                throw new BusinessException("图形验证码已失效");
            }
            // 判断验证码
            Boolean result = true;
            if (req.getVerCode() == null || !redisCode.equals(req.getVerCode().trim().toLowerCase())) {
                result = false;
            }
            return ResultInfo.success(result);
        }finally {
            cacheUtil.delete(EhcacheElementType.CAPTCHA,req.getKey());
        }
    }
}
